package com.jiantong.work.impl.dao;

import com.google.common.collect.Maps;
import com.jiantong.work.enums.DocumentsDeleteFlag;
import com.jiantong.work.model.RetailImmunizationRecord;
import io.terminus.common.model.Paging;
import io.terminus.common.mysql.dao.MyBatisDao;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * Created by mz on 18/9/17.
 *
 */
@Repository
public class RetailImmunizationRecordDao extends MyBatisDao<RetailImmunizationRecord>{

    /**
     * 返回当前单据的编码的最大值
     * @param number 除去流水号的前缀
     * @return string
     */
    public String findCurrentMaxNumber(String number){
        return getSqlSession().selectOne(sqlId("findCurrentMaxNumber"),number);
    }

    /**
     * 查询单据当前的状态
     * @param id 主键ID
     * @return Integer
     */
    public Integer findStatusById(Long id){
        return getSqlSession().selectOne(sqlId("findStatusById"),id);
    }

    /**
     * 分页查询多个散户养殖场的 免疫记录情况
     * @param offset 从
     * @param limit 多少条
     * @param criteria 参数
     * @return Paging<RetailImmunizationRecord>
     */
    public Paging<RetailImmunizationRecord> pagingMulti(Integer offset, Integer limit, Map<String, Object> criteria){
        if(criteria == null) {
            criteria = Maps.newHashMap();
        }

        Long total = (Long)this.sqlSession.selectOne(this.sqlId("countMulti"), criteria);
        if(total <= 0L) {
            return new Paging<>(0L, Collections.emptyList());
        } else {
            criteria.put("offset", offset);
            criteria.put("limit", limit);
            List<RetailImmunizationRecord> datas = this.sqlSession.selectList(this.sqlId("pagingMulti"), criteria);
            return new Paging<>(total, datas);
        }
    }

    /**
     * 查询出一个是否免疫的list
     * @param breedFactoryIds 养殖场ids
     * @return List<Boolean>
     */
    public List<Boolean> countIsVaccine(List<Long> breedFactoryIds){
        List<Boolean> list = new ArrayList<>();
        for(Long breedFactoryId : breedFactoryIds){
            Map<String, Object> criteria = Maps.newHashMap();
            criteria.put("breedFactoryId",breedFactoryId);
            criteria.put("status",1);
            criteria.put("deleteFlag", DocumentsDeleteFlag.NORMAL.value());
            Long count = getSqlSession().selectOne(sqlId("countIsVaccine"),criteria);
            if(count > 0L) list.add(Boolean.TRUE);
            else list.add(Boolean.FALSE);
        }
        return list;
    }

    /**
     * 溯源
     * @param criteria 参数
     * @return RetailImmunizationRecord
     */
    public RetailImmunizationRecord findByEarNumber(Map<String , Object> criteria){
        return getSqlSession().selectOne(sqlId("findByMarkNumber"),criteria);
    }
}
